<template>
  <div>
    <div class="week">
      <span v-for="item in weekList" :key="item">{{ item }}</span>
    </div>
    <div class="main">
      <div
        v-for="(item, index) in totalDate"
        :key="item.month"
        class="year-month"
      >
        <div class="month">{{ item.month.replace('-', '年') }}月</div>
        <div class="date">
          <div
            v-for="(item2, index1) in item.dateList"
            :key="item2.date"
            class="day"
          >
            <span>{{
              index == 0 && index1 == 0
                ? '明天'
                : item2.date.substring(item2.date.length - 2)
            }}</span>
            <div class="time">
              <div
                v-for="item3 in item2.timeSelect"
                :key="item3"
                :class="[
                  cssList.indexOf(`${item2.date} ${item3}`) > -1
                    ? 'active'
                    : 'default',
                ]"
                @click="selectTime(item2.date, item3)"
              >
                <span
                  :class="
                    publishedList.indexOf(`${item2.date} ${item3}:00`) > -1
                      ? 'disabled'
                      : ''
                  "
                  >{{
                    publishedList.indexOf(`${item2.date} ${item3}:00`) > -1
                      ? '已发布'
                      : item3
                  }}</span
                >
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import dayjs from 'dayjs'
import { dateFormatter, getTime, getLaterDate } from '../utils'
import { publishSave, getpublishQueryList } from '../api'
import { FormInstance, Toast } from 'vant'
import { useRouter } from 'vue-router'

export default defineComponent({
  setup() {
    const router = useRouter()
    let week = ['日', '一', '二', '三', '四', '五', '六']
    const { totalDate, weekList } = getTwoWeeksDate(week)
    let list: any[] = []
    let cssList = ref<string[]>([])
    let publishedList = ref<any[]>([])

    const user = JSON.parse(localStorage.getItem('fock_user_data')!)

    const params = {
      beginDate: getLaterDate(1),
      endDate: getLaterDate(31),
      tenantId: user.tenantId,
      userId: user.userId,
    }
    getpublishQueryList(params).then((res) => {
      let data = res.data.data
      let list = res
      for (let i in data) {
        if (data[i].length > 0) {
          data[i].forEach((item: any) => {
            publishedList.value.push(item.startTime)
          })
        }
      }
    })

    const selectTime = (date: any, time: string) => {
      if (publishedList.value.indexOf(`${date} ${time}:00`) > -1) {
        return
      }

      if (date.length > 0) {
        const isDate: any[] = list.filter((item) => {
          return item.startTime == `${date} ${time}:00`
        })
        if (isDate.length > 0) {
          list = list.filter((item) => {
            return item.startTime != `${date} ${time}:00`
          })
          cssList.value = cssList.value.filter((item) => {
            return item != `${date} ${time}`
          })
        } else {
          list.push(addDate(date, time))
          cssList.value.push(`${date} ${time}`)
        }
      } else {
        list.push(addDate(date, time))
        cssList.value.push(`${date} ${time}`)
      }
    }

    return {
      totalDate,
      weekList,
      cssList,
      publishedList,
      selectTime,
      async handleSubmit() {
        const { data } = await publishSave(list)
        Toast('提交成功')
        router.push({ name: 'ReserveRecord' })
      },
    }
  },
})

interface Date {
  date: any
  timeSelect: Array<string>
  week: string
}

function getTwoWeeksDate(week: string[]) {
  let timeSelect = [
    '09:00',
    '10:00',
    '11:00',
    '12:00',
    '13:00',
    '14:00',
    '15:00',
    '16:00',
    '17:00',
    '18:00',
    '19:00',
    '20:00',
    '21:00',
  ]
  let dateList: Date[] = []
  let totalDate = []
  for (let i = 0; i < 31; i++) {
    let obj = {
      date: getLaterDate(i + 1),
      timeSelect,
      week: week[
        parseInt(
          dayjs()
            .add(i + 1, 'day')
            .format('d')
        )
      ],
    }
    dateList.push(obj)
  }
  let weekList = getWeekList(dateList)
  let monthList = getMonth(dateList, weekList, week)

  for (let i in monthList) {
    let dateObj = {
      month: i,
      dateList: monthList[i].list,
    }
    totalDate.push(dateObj)
  }
  console.log(totalDate)
  return { totalDate, weekList }
}

function getMonth<T>(dateList: T[], weekList: string[], week: string[]) {
  let weeks: any = {}
  dateList.forEach((item: Record<string, any>) => {
    let month = item.date.substring(0, 7)
    if (!weeks[month]) {
      weeks[month] = {
        list: [],
      }
      let length = 0
      weekList.forEach((item2, index) =>
        item2 === week[new Date(item.date).getDay()] ? (length = index) : ''
      )
      for (let i = 0; i < length; i++) {
        let obj = {
          date: '',
        }
        weeks[month].list.push(obj)
      }
      weeks[month].list.push(item)
    } else {
      weeks[month].list.push(item)
    }
  })

  return weeks
}

function getWeekList(dateList: Date[]) {
  let weekList: string[] = []
  dateList.forEach((item: Date, index) => {
    if (index < 7) {
      weekList.push(item.week)
    }
  })

  return weekList
}

function addDate(date: string, time: string) {
  let dateObj = {
    startTime: `${date} ${time}:00`,
    endTime: `${date} ${time.substring(0, 2)}:59:59`,
    deadline: `${date} 23:59:59`,
    maxNum: 1,
    description: '',
    status: 1,
  }
  return dateObj
}
</script>

<style lang="less" scoped>
.week {
  // display: flex;
  // justify-content: space-around;
  // align-items: center;
  // font-size: 13px;
  // padding: 10px;
  display: grid;
  font-size: 13px;
  padding: 10px;
  grid-template-columns: repeat(7, 13%);
  grid-column-gap: 1.4%;

  span {
    text-align: center;
  }
}

.main {
  .year-month {
    .month {
      text-align: center;
      font-size: 14px;
    }

    .date {
      display: grid;
      font-size: 13px;
      padding: 10px;
      grid-template-columns: repeat(7, 13%);
      grid-column-gap: 1.4%;

      .day {
        display: inline-grid;
        text-align: center;
        margin-top: 20px;

        > span {
          height: 16px;
          line-height: 16px;
        }

        .time {
          display: flex;
          flex-direction: column;

          div {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            line-height: 45px;
            margin-top: 10px;
          }
        }
      }
    }
  }
}

.active {
  background: rgb(58, 219, 188);
  color: white;
}

.default {
  background: rgb(240, 240, 240);
  color: black;
}

.disabled {
  opacity: 0.4;
  transform: scale(0.85);
  display: inline-block;
}
</style>
